// WebRTC客户端实现

// 配置
const config = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' },
        { urls: 'stun:stun2.l.google.com:19302' }
    ]
};

// DOM元素
const remoteVideo = document.getElementById('remote-video');
const connectBtn = document.getElementById('connect-btn');
const disconnectBtn = document.getElementById('disconnect-btn');
const statusIndicator = document.getElementById('status-indicator');
const connectionStats = document.getElementById('connection-stats');

// WebRTC变量
let peerConnection = null;
let signaling = null;
let statsInterval = null;

// 连接按钮事件
connectBtn.addEventListener('click', startConnection);

// 断开按钮事件
disconnectBtn.addEventListener('click', closeConnection);

// 初始化WebSocket信令连接
function initSignaling() {
    // 获取当前主机名和协议
    const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${location.host}/signaling`;
    
    signaling = new WebSocket(wsUrl);
    
    signaling.onopen = () => {
        console.log('信令服务器连接成功');
        // 发送加入房间消息
        sendSignalingMessage({
            type: 'join',
            room: 'desktop'
        });
    };
    
    signaling.onmessage = (event) => {
        const message = JSON.parse(event.data);
        handleSignalingMessage(message);
    };
    
    signaling.onerror = (error) => {
        console.error('信令连接错误:', error);
        updateStatus('连接错误', false);
    };
    
    signaling.onclose = () => {
        console.log('信令连接关闭');
        if (peerConnection) {
            closeConnection();
        }
    };
}

// 发送信令消息
function sendSignalingMessage(message) {
    if (signaling && signaling.readyState === WebSocket.OPEN) {
        signaling.send(JSON.stringify(message));
    }
}

// 处理信令消息
async function handleSignalingMessage(message) {
    switch (message.type) {
        case 'offer':
            if (!peerConnection) {
                createPeerConnection();
            }
            await peerConnection.setRemoteDescription(new RTCSessionDescription(message));
            const answer = await peerConnection.createAnswer();
            await peerConnection.setLocalDescription(answer);
            sendSignalingMessage({
                type: 'answer',
                sdp: peerConnection.localDescription
            });
            break;
            
        case 'answer':
            try {
                // 确保message包含正确的SDP格式
                const answerDesc = {
                    type: message.sdp?.type || message.type,
                    sdp: message.sdp?.sdp || message.sdp
                };
                await peerConnection.setRemoteDescription(new RTCSessionDescription(answerDesc));
            } catch (e) {
                console.error('设置远程描述失败:', e);
                updateStatus('连接错误', false);
            }
            break;
            
        case 'candidate':
            if (message.candidate) {
                try {
                    await peerConnection.addIceCandidate(new RTCIceCandidate(message.candidate));
                } catch (e) {
                    console.error('添加ICE候选者失败:', e);
                }
            }
            break;
            
        case 'ready':
            // 服务器准备好了，可以开始连接
            startPeerConnection();
            break;
            
        case 'error':
            console.error('服务器错误:', message.message);
            updateStatus(`错误: ${message.message}`, false);
            break;
    }
}

// 创建对等连接
function createPeerConnection() {
    console.log('创建对等连接...');
    peerConnection = new RTCPeerConnection(config);
    
    // 处理ICE候选者
    peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
            sendSignalingMessage({
                type: 'candidate',
                candidate: event.candidate
            });
        }
    };
    
    // 处理连接状态变化
    peerConnection.onconnectionstatechange = () => {
        console.log('连接状态:', peerConnection.connectionState);
        switch (peerConnection.connectionState) {
            case 'connected':
                updateStatus('已连接', true);
                startStatsMonitoring();
                break;
            case 'disconnected':
            case 'failed':
                updateStatus('连接断开', false);
                stopStatsMonitoring();
                break;
            case 'closed':
                updateStatus('连接关闭', false);
                stopStatsMonitoring();
                break;
        }
    };
    
    // 处理ICE连接状态变化
    peerConnection.oniceconnectionstatechange = () => {
        console.log('ICE连接状态:', peerConnection.iceConnectionState);
    };
    
    // 处理信令状态变化
    peerConnection.onsignalingstatechange = () => {
        console.log('信令状态:', peerConnection.signalingState);
    };
    
    // 处理远程流
    peerConnection.ontrack = (event) => {
        console.log('收到远程轨道', event.track.kind);
        
        // 记录轨道类型，帮助调试
        console.log('轨道类型:', event.track.kind, '轨道ID:', event.track.id, '轨道标签:', event.track.label);
        
        if (event.streams && event.streams[0]) {
            console.log('设置视频源，流ID:', event.streams[0].id);
            
            // 确保之前的视频流被正确清理
            if (remoteVideo.srcObject) {
                console.log('清理之前的视频流');
                const tracks = remoteVideo.srcObject.getTracks();
                tracks.forEach(track => track.stop());
            }
            
            remoteVideo.srcObject = event.streams[0];
            
            // 确保视频元素正确播放
            remoteVideo.onloadedmetadata = () => {
                console.log('视频元数据已加载, 分辨率:', remoteVideo.videoWidth, 'x', remoteVideo.videoHeight);
                
                // 确保视频元素可见
                remoteVideo.style.display = 'block';
                
                // 尝试播放视频
                const playPromise = remoteVideo.play();
                if (playPromise !== undefined) {
                    playPromise
                        .then(() => {
                            console.log('视频开始播放');
                        })
                        .catch(e => {
                            console.error('视频播放失败:', e);
                            // 尝试自动恢复播放
                            console.log('1秒后尝试重新播放...');
                            setTimeout(() => {
                                console.log('尝试重新播放...');
                                remoteVideo.play().catch(e => {
                                    console.error('重试播放失败:', e);
                                    // 再次尝试
                                    setTimeout(() => {
                                        console.log('再次尝试重新播放...');
                                        remoteVideo.play().catch(e => console.error('第二次重试播放失败:', e));
                                    }, 1000);
                                });
                            }, 1000);
                        });
                }
            };
            
            // 添加错误处理
            remoteVideo.onerror = (error) => {
                console.error('视频元素错误:', error);
            };
            
            // 监听视频错误
            remoteVideo.onerror = (e) => {
                console.error('视频错误:', e);
            };
            
            // 监听视频播放状态
            remoteVideo.addEventListener('playing', () => {
                console.log('视频正在播放，分辨率:', remoteVideo.videoWidth, 'x', remoteVideo.videoHeight);
            });
            
            remoteVideo.addEventListener('waiting', () => {
                console.log('视频等待数据');
            });
            
            remoteVideo.addEventListener('stalled', () => {
                console.log('视频停滞');
            });
            
            // 监听视频状态
            remoteVideo.addEventListener('playing', () => {
                console.log('视频正在播放');
            });
            
            remoteVideo.addEventListener('waiting', () => {
                console.log('视频等待数据');
            });
            
            remoteVideo.addEventListener('stalled', () => {
                console.log('视频停滞');
            });
        } else {
            console.warn('收到轨道但没有流');
        }
    };
}

// 开始对等连接
async function startPeerConnection() {
    if (!peerConnection) {
        createPeerConnection();
    }
    
    try {
        // 添加接收视频的transceiver
        peerConnection.addTransceiver('video', { direction: 'recvonly' });
        
        // 创建offer
        const offer = await peerConnection.createOffer();
        await peerConnection.setLocalDescription(offer);
        
        // 发送offer到服务器
        sendSignalingMessage({
            type: 'offer',
            sdp: peerConnection.localDescription
        });
    } catch (error) {
        console.error('创建offer失败:', error);
        updateStatus('连接失败', false);
    }
}

// 开始连接
function startConnection() {
    updateStatus('正在连接...', false);
    connectBtn.disabled = true;
    disconnectBtn.disabled = false;
    
    // 初始化信令连接
    initSignaling();
}

// 关闭连接
function closeConnection() {
    // 停止统计监控
    stopStatsMonitoring();
    
    // 关闭对等连接
    if (peerConnection) {
        peerConnection.close();
        peerConnection = null;
    }
    
    // 关闭信令连接
    if (signaling) {
        signaling.close();
        signaling = null;
    }
    
    // 清除视频
    remoteVideo.srcObject = null;
    
    // 更新UI
    updateStatus('未连接', false);
    connectBtn.disabled = false;
    disconnectBtn.disabled = true;
    connectionStats.textContent = '';
}

// 更新状态显示
function updateStatus(text, connected) {
    statusIndicator.textContent = text;
    if (connected) {
        statusIndicator.classList.add('connected');
    } else {
        statusIndicator.classList.remove('connected');
    }
}

// 开始统计监控
function startStatsMonitoring() {
    if (statsInterval) {
        clearInterval(statsInterval);
    }
    
    statsInterval = setInterval(async () => {
        if (!peerConnection) return;
        
        try {
            const stats = await peerConnection.getStats();
            let statsOutput = '';
            
            stats.forEach(report => {
                if (report.type === 'inbound-rtp' && report.kind === 'video') {
                    statsOutput += `分辨率: ${report.frameWidth}x${report.frameHeight}\n`;
                    statsOutput += `帧率: ${report.framesPerSecond}\n`;
                    statsOutput += `接收比特率: ${Math.round(report.bytesReceived * 8 / (report.timestamp - report.lastTimestamp) / 1000)} kbps\n`;
                    statsOutput += `丢包率: ${report.packetsLost / (report.packetsReceived + report.packetsLost) * 100}%\n`;
                }
                
                if (report.type === 'candidate-pair' && report.state === 'succeeded') {
                    statsOutput += `往返时间: ${report.currentRoundTripTime * 1000}ms\n`;
                }
            });
            
            connectionStats.textContent = statsOutput || '无可用统计数据';
        } catch (e) {
            console.error('获取统计数据失败:', e);
        }
    }, 1000);
}

// 停止统计监控
function stopStatsMonitoring() {
    if (statsInterval) {
        clearInterval(statsInterval);
        statsInterval = null;
    }
}

// 页面卸载时关闭连接
window.addEventListener('beforeunload', closeConnection);